package tcp.filetransfer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

import networkdescriptor.NetworkDescriptor;

import constants.NetworkConstants;

public class FileTransferClient {

	public static boolean requestFileDownload(NetworkDescriptor commandServer, String filename,String destination){
		//Upload the file to the suggested client
		try{
		Socket downloadClient = new Socket();
		downloadClient.connect(new InetSocketAddress("localhost", NetworkConstants.DEFAULT_FD_PORT));
		if(downloadClient.isConnected()){
			File downloadLocation = new File(destination+File.separatorChar+filename);
			PrintWriter fileOut = new PrintWriter(new FileOutputStream(downloadLocation),true);
			PrintWriter socketOut = new PrintWriter(downloadClient.getOutputStream(),true); 
			BufferedReader socketIn = new BufferedReader(new InputStreamReader(downloadClient.getInputStream()));
			String socketLine = null;
			socketOut.println("HELO FTDWN");
			socketOut.println(filename);
			socketLine = socketIn.readLine() ;
			if(socketLine != null && socketLine.equalsIgnoreCase("OK")){
				while((socketLine = socketIn.readLine()) != null && !socketLine.equalsIgnoreCase("EOF")){
					if(!socketLine.equalsIgnoreCase("EOF")){
						fileOut.println(socketLine);
					}
				}

			}
			socketOut.close();
			socketIn.close();
			downloadClient.close();
			fileOut.flush();
			fileOut.close();
		}
		}catch(IOException e){
			e.printStackTrace();
			//TODO fix this
			return false;
			
		}catch(Exception e){
			return false;
		}
		return true;
	}
	public static void requestFileUpload(String hostname, int portNumber,File fileToUpload){
		//Protocol is talk to Govenor and ask where best to upload file
		
		//Upload the file to the suggested client
		try{
		Socket uploadClient = new Socket();
		uploadClient.connect(new InetSocketAddress(hostname, portNumber));
		if(uploadClient.isConnected()){
		
			BufferedReader fileIn = new BufferedReader(new FileReader(fileToUpload));
			PrintWriter socketOut = new PrintWriter(uploadClient.getOutputStream(),true); 
			BufferedReader socketIn = new BufferedReader(new InputStreamReader(uploadClient.getInputStream()));
			String fileLine = null;
			String socketLine = null;
			socketOut.println("HELO FTUP");
			socketOut.println(fileToUpload.getName());
			socketLine = socketIn.readLine() ;
			if(socketLine != null && socketLine.equalsIgnoreCase("OK")){
				while((fileLine = fileIn.readLine()) != null){
					socketOut.println(fileLine);
				}

			}
			socketOut.close();
			socketIn.close();
			uploadClient.close();
			fileIn.close();
		}
		}catch(IOException e){
			//TODO fix this
			e.printStackTrace();
		}
		
		
	}
}
